//
//  NewsCollectListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/5/11.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "NewsCollectListViewController.h"
#import "CommonWebViewController.h"
#import "NewsCollectionListCell.h"
#import "NewsListItemModel.h"
@interface NewsCollectListViewController ()<UITableViewDelegate,UITableViewDataSource,NewsCollectionListCellDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,assign)NSInteger pageIndex;

@property (nonatomic,strong)NewsListItemModel *currentModel;

@property (nonatomic,strong)UIImageView *noDataIcon;
@property (nonatomic,strong)UILabel *noDataLb;

@end

@implementation NewsCollectListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = NO;

}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageIndex = 1;
   
    [self setUI];
    
    [self registNote];
    
    [self showDataLoadState];
    [self loadDataSource];
    
}

- (void)setUI{
    
    self.navigationItem.title = @"收藏夹";
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.view);
        make.left.equalTo(self.view).offset(16);
        make.right.equalTo(self.view).offset(-16);
    }];
    
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf loadDataSource];
    }];
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf loadDataSource];
    }];
    
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    
    self.tableView.mj_header = header;
    self.tableView.mj_footer = footer;
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    
    self.noDataLb = [[UILabel alloc]init];
    self.noDataLb.text = @"无内容";
    self.noDataLb.textColor = RGBA(170, 170, 170, 1);
    self.noDataLb.font = font(14);
    [self.view addSubview:self.noDataLb];
    [self.noDataLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
    }];
    
    self.noDataIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"no_collect_data_tag"]];
    [self.view addSubview:self.noDataIcon];
    [self.noDataIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.noDataLb.mas_top).offset(-12);
    }];
    
    self.noDataLb.hidden = YES;
    self.noDataIcon.hidden = YES;
    

}

- (void)registNote{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateCollectList:) name:@"refreshNewsCollectionList" object:nil];
}
- (void)updateCollectList:(NSNotification *)note{
    NSNumber *newsId = note.userInfo[@"newsId"];
    BOOL status = [note.userInfo[@"status"] boolValue];
    if (status) {
        // 插入第一条数据
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetNewsDetail];
        param[@"id"] = newsId;
        [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetNewsDetail) parames:param success:^(id responseObj) {
            NewsListItemModel *itemModel = [NewsListItemModel mj_objectWithKeyValues:responseObj[RESPONSE]];
            [self.dataArray insertObject:itemModel atIndex:0];
            [self.tableView reloadData];
            
            self.noDataLb.hidden = self.dataArray.count > 0;
            self.noDataIcon.hidden = self.dataArray.count > 0;
            
            self.tableView.mj_footer.hidden = self.dataArray.count == 0;
            
        } failure:^(id error) {
                    
        }];
    }else{
        __block NSInteger index = -1;
        [self.dataArray enumerateObjectsUsingBlock:^(NewsListItemModel  * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.projectId isEqualToNumber:newsId]) {
                index = idx;
                *stop = YES;
            }
        }];
        if (index != -1) {
            [self.dataArray removeObjectAtIndex:index];
            [self.tableView reloadData];
            
            self.noDataLb.hidden = self.dataArray.count > 0;
            self.noDataIcon.hidden = self.dataArray.count > 0;
            
            self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        }
    }
    
}

- (void)loadDataSource{
    
    NSNumber *lastId = nil;
    
    if (self.dataArray != 0 && self.pageIndex > 1) {
        NewsListItemModel *itemModel = [self.dataArray lastObject];
        lastId = itemModel.id;
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetNewsMarkList];
    param[@"pageIndex"] = @(self.pageIndex);
    param[@"pageSize"] = @(10);
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lastId"] = lastId;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetNewsMarkList) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        if ([self.tableView.mj_header isRefreshing]) {
            [self.tableView.mj_header endRefreshing];
        }
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        

        if (self.pageIndex == 1) {
            self.dataArray = [NewsListItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[NewsListItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
        }
        
        self.noDataLb.hidden = self.dataArray.count > 0;
        self.noDataIcon.hidden = self.dataArray.count > 0;
        
        CGFloat bottom = self.tableView.mj_insetB;
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            if (self.tableView.mj_footer.cl_height == 44.0f) {
                self.tableView.mj_footer.cl_height = 138.0f;
                if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                    self.tableView.mj_insetB = 138.0f;
                }
            }
        }else{
            [self.tableView.mj_footer resetNoMoreData];
            if (self.tableView.mj_footer.cl_height == 138.0f) {
                self.tableView.mj_footer.cl_height = 44.0f;
                if (bottom == 138.0f) {
                    self.tableView.mj_insetB = 44.0f;
                }
            }
        }
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        
        [self.tableView reloadData];
            
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
}

- (void)cancelCollect{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:DeleteNewsMark];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"id"] = self.currentModel.id;
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DeleteNewsMark) parames:param success:^(id responseObj) {
       
        NSInteger index = [self.dataArray indexOfObject:self.currentModel];
        
        [self.dataArray removeObject:self.currentModel];
        if (self.dataArray.count == 0) {
            if (self.tableView.mj_footer.state == MJRefreshStateNoMoreData) {
                self.noDataLb.hidden = NO;
                self.noDataIcon.hidden = NO;
            }else{
                // 判断是否数量等于0
                if (self.dataArray.count == 0) {
                    self.pageIndex++;
                    [self loadDataSource];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [self.tableView deleteSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        self.tableView.mj_footer.hidden = self.dataArray.count == 0;
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}


- (void)removeMethod{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定取消收藏？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
        
        [self cancelCollect];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
             //往alertViewController上添加alertAction
    [alertController addAction:confirmAction];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsCollectionListCell *cell = [NewsCollectionListCell cellWithTableView:tableView];
    cell.delegate = self;
    [cell setItemModel:self.dataArray[indexPath.section]];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 16.0;
    }
    return 24.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

#pragma mark - NewsCollectionListCellDelegate
- (void)showNewsDetailByCurrentModel:(NewsListItemModel *)currentModel{
    CommonWebViewController *dtlVC = [[CommonWebViewController alloc]init];
    dtlVC.webUrl = [NSString stringWithFormat:@"%@lesson/news/%@?isApp=true&userId=%@",HtmlUrl,currentModel.projectId,[RPAppManager getCustomerId]];
    dtlVC.isDark = NO;
    [self.navigationController pushViewController:dtlVC animated:YES];

}

#pragma mark - other
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}


- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDefault) title:@"取消收藏" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        self.currentModel = self.dataArray[indexPath.section];
        [self removeMethod];
    }];
    deleteAction.backgroundColor = RGBA(232, 85, 83, 1);
    return @[deleteAction];
}

- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self setupSlideBtnWithEditingIndexPath:indexPath];
    });
}

- (void)setupSlideBtnWithEditingIndexPath:(NSIndexPath *)editingIndexPath {
    if (@available(iOS 13.0, *)) {
        for (UIView *subView in self.tableView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"_UITableViewCellSwipeContainerView")] && [subView.subviews count] >= 1) {
                UIView *remarkContentView = subView.subviews.firstObject;
                UIButton *button = remarkContentView.subviews.firstObject;
                button.titleLabel.font = font(12);
            }
        }
        return;
    }
    if (@available(iOS 11.0, *)) {
        for (UIView *subView in self.tableView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UISwipeActionPullView")] && [subView.subviews count] >= 1) {
                UIView *remarkContentView = subView;
                UIButton *button = remarkContentView.subviews.firstObject;
                button.titleLabel.font = font(12);
            }
        }
        return;
    }
    NewsCollectionListCell *cell = [self.tableView cellForRowAtIndexPath:editingIndexPath];
    for (UIView *subView in cell.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UITableViewCellDeleteConfirmationView")] && [subView.subviews count] >= 1) {
            UIView *remarkContentView = subView;
            UIButton *button = remarkContentView.subviews.firstObject;
            button.titleLabel.font = font(12);
        }
    }
}

@end
